package com.group3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.group3.dao.*;
import com.group3.entity.*;
import com.group3.service.BehaviorAnalysisService;
import com.group3.vo.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class BehaviorAnalysisServiceImpl implements BehaviorAnalysisService {

    @Resource
    private BrowseBehaviorMapper browseBehaviorMapper;

    @Resource
    private ClickBehaviorMapper clickBehaviorMapper;

    @Resource
    private PurchaseBehaviorMapper purchaseBehaviorMapper;

    @Resource
    private FavoriteBehaviorMapper favoriteBehaviorMapper;

    @Resource
    private CommentBehaviorMapper commentBehaviorMapper;

    @Resource
    private UserProfileMapper userProfileMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public UserBehaviorStatsVO getUserBehaviorStats(Long userId) {
        String cacheKey = "user_stats:" + userId;
        UserBehaviorStatsVO cached = (UserBehaviorStatsVO) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }

        UserBehaviorStatsVO stats = new UserBehaviorStatsVO();
        stats.setUserId(userId);

        // 使用LambdaQueryWrapper统计各种行为
        stats.setBrowseCount(browseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<BrowseBehavior>()
                        .eq(BrowseBehavior::getUserId, userId)
                        .eq(BrowseBehavior::getDeleted, 0)
        ));

        stats.setClickCount(clickBehaviorMapper.selectCount(
                new LambdaQueryWrapper<ClickBehavior>()
                        .eq(ClickBehavior::getUserId, userId)
                        .eq(ClickBehavior::getDeleted, 0)
        ));

        stats.setPurchaseCount(purchaseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<PurchaseBehavior>()
                        .eq(PurchaseBehavior::getUserId, userId)
                        .eq(PurchaseBehavior::getDeleted, 0)
        ));

        stats.setFavoriteCount(favoriteBehaviorMapper.selectCount(
                new LambdaQueryWrapper<FavoriteBehavior>()
                        .eq(FavoriteBehavior::getUserId, userId)
                        .eq(FavoriteBehavior::getDeleted, 0)
        ));

        stats.setCommentCount(commentBehaviorMapper.selectCount(
                new LambdaQueryWrapper<CommentBehavior>()
                        .eq(CommentBehavior::getUserId, userId)
                        .eq(CommentBehavior::getDeleted, 0)
        ));

        // 计算活跃度
        int activityScore = calculateActivityScore(
                stats.getBrowseCount(),
                stats.getClickCount(),
                stats.getPurchaseCount(),
                stats.getFavoriteCount(),
                stats.getCommentCount()
        );
        stats.setActivityScore(activityScore);

        // 存入缓存，有效期1小时
        redisTemplate.opsForValue().set(cacheKey, stats, 1, TimeUnit.HOURS);

        cached.setUserId(1L);
        cached.setBrowseCount(25);
        cached.setClickCount(20);
        cached.setPurchaseCount(5);
        cached.setFavoriteCount(1);
        cached.setCommentCount(100);



        return stats;
    }

    @Override
    public ProductBehaviorStatsVO getProductBehaviorStats(Long productId) {
        String cacheKey = "product_stats:" + productId;
        ProductBehaviorStatsVO cached = (ProductBehaviorStatsVO) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }

        ProductBehaviorStatsVO stats = new ProductBehaviorStatsVO();
        stats.setProductId(productId);

        // 统计浏览行为 - 使用LambdaQueryWrapper
        stats.setBrowseCount(browseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<BrowseBehavior>()
                        .eq(BrowseBehavior::getProductId, productId)
                        .eq(BrowseBehavior::getDeleted, 0)
        ));

        // 统计点击行为
        stats.setClickCount(clickBehaviorMapper.selectCount(
                new LambdaQueryWrapper<ClickBehavior>()
                        .eq(ClickBehavior::getProductId, productId)
                        .eq(ClickBehavior::getDeleted, 0)
        ));

        // 统计购买行为
        stats.setPurchaseCount(purchaseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<PurchaseBehavior>()
                        .eq(PurchaseBehavior::getProductId, productId)
                        .eq(PurchaseBehavior::getDeleted, 0)
        ));

        // 统计收藏行为
        stats.setFavoriteCount(favoriteBehaviorMapper.selectCount(
                new LambdaQueryWrapper<FavoriteBehavior>()
                        .eq(FavoriteBehavior::getProductId, productId)
                        .eq(FavoriteBehavior::getDeleted, 0)
        ));

        // 统计评论行为
        stats.setCommentCount(commentBehaviorMapper.selectCount(
                new LambdaQueryWrapper<CommentBehavior>()
                        .eq(CommentBehavior::getProductId, productId)
                        .eq(CommentBehavior::getDeleted, 0)
        ));

        // 计算转化率
        if (stats.getBrowseCount() > 0) {
            double conversionRate = (double) stats.getPurchaseCount() / stats.getBrowseCount() * 100;
            stats.setConversionRate(BigDecimal.valueOf(conversionRate).setScale(2, RoundingMode.HALF_UP));
        } else {
            stats.setConversionRate(BigDecimal.ZERO);
        }

        // 存入缓存，有效期30分钟
        redisTemplate.opsForValue().set(cacheKey, stats, 30, TimeUnit.MINUTES);

        return stats;
    }

    @Override
    public LiveRoomStatsVO getLiveRoomStats(Long liveId) {
        String cacheKey = "live_stats:" + liveId;
        LiveRoomStatsVO cached = (LiveRoomStatsVO) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }

        LiveRoomStatsVO stats = new LiveRoomStatsVO();
        stats.setLiveId(liveId);

        // 统计浏览行为（观众数）- 使用LambdaQueryWrapper
        int browseCount = browseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<BrowseBehavior>()
                        .eq(BrowseBehavior::getLiveId, liveId)
                        .eq(BrowseBehavior::getDeleted, 0)
        );
        stats.setViewerCount(browseCount);

        // 统计点击行为 - 使用LambdaQueryWrapper
        int clickCount = clickBehaviorMapper.selectCount(
                new LambdaQueryWrapper<ClickBehavior>()
                        .eq(ClickBehavior::getLiveId, liveId)
                        .eq(ClickBehavior::getDeleted, 0)
        );

        // 统计评论行为 - 使用LambdaQueryWrapper
        int commentCount = commentBehaviorMapper.selectCount(
                new LambdaQueryWrapper<CommentBehavior>()
                        .eq(CommentBehavior::getLiveId, liveId)
                        .eq(CommentBehavior::getDeleted, 0)
        );

        // 计算互动行为（点击+评论）
        int interactionCount = clickCount + commentCount;
        stats.setInteractionCount(interactionCount);

        // 统计购买行为 - 使用LambdaQueryWrapper
        int purchaseCount = purchaseBehaviorMapper.selectCount(
                new LambdaQueryWrapper<PurchaseBehavior>()
                        .eq(PurchaseBehavior::getLiveId, liveId)
                        .eq(PurchaseBehavior::getDeleted, 0)
        );
        stats.setPurchaseCount(purchaseCount);

        // 计算互动率
        if (browseCount > 0) {
            double interactionRate = (double) interactionCount / browseCount * 100;
            stats.setInteractionRate(BigDecimal.valueOf(interactionRate).setScale(2, RoundingMode.HALF_UP));
        } else {
            stats.setInteractionRate(BigDecimal.ZERO);
        }

        // 存入缓存，有效期15分钟
        redisTemplate.opsForValue().set(cacheKey, stats, 15, TimeUnit.MINUTES);

        return stats;
    }

    @Override
    public List<UserProfileVO> getUserProfiles(List<Long> userIds) {
        List<UserProfileVO> profiles = new ArrayList<>();
        List<Long> uncachedUserIds = new ArrayList<>();

        // 先从缓存获取
        for (Long userId : userIds) {
            String cacheKey = "user_profile:" + userId;
            UserProfileVO cached = (UserProfileVO) redisTemplate.opsForValue().get(cacheKey);
            if (cached != null) {
                profiles.add(cached);
            } else {
                uncachedUserIds.add(userId);
            }
        }

        // 如果缓存未命中，从数据库查询
        if (!uncachedUserIds.isEmpty()) {
            List<UserProfile> dbProfiles = userProfileMapper.selectBatchIds(uncachedUserIds);
            for (UserProfile profile : dbProfiles) {
                UserProfileVO vo = convertToVO(profile);
                profiles.add(vo);

                // 存入缓存
                String cacheKey = "user_profile:" + profile.getUserId();
                redisTemplate.opsForValue().set(cacheKey, vo, 1, TimeUnit.DAYS);
            }
        }

        return profiles;
    }

    @Override
    public List<RecommendationVO> getRecommendations(Long userId) {
        String cacheKey = "recommendations:" + userId;
        List<RecommendationVO> cached = (List<RecommendationVO>) redisTemplate.opsForValue().get(cacheKey);
        if (cached != null) {
            return cached;
        }

        // 获取用户画像
        UserProfileVO profile = getUserProfiles(Collections.singletonList(userId)).get(0);

        // 模拟推荐算法
        List<RecommendationVO> recommendations = new ArrayList<>();

        // 基于用户兴趣推荐
        if (profile.getInterests() != null && !profile.getInterests().isEmpty()) {
            String[] interests = profile.getInterests().split(",");
            for (String interest : interests) {
                RecommendationVO vo = new RecommendationVO();
                vo.setProductId(1000L + interest.hashCode() % 100); // 模拟产品ID
                vo.setProductName(interest + "推荐商品");
                vo.setScore(80 + new Random().nextInt(20)); // 模拟推荐分数
                recommendations.add(vo);
            }
        }

        // 基于购买历史推荐
        if (profile.getPurchasePower().compareTo(BigDecimal.valueOf(500)) > 0) {
            RecommendationVO vo = new RecommendationVO();
            vo.setProductId(2000L + userId % 100);
            vo.setProductName("高端精选商品");
            vo.setScore(90);
            recommendations.add(vo);
        }

        // 按推荐分数排序
        recommendations.sort((a, b) -> b.getScore() - a.getScore());

        // 限制返回数量
        if (recommendations.size() > 10) {
            recommendations = recommendations.subList(0, 10);
        }

        // 存入缓存，有效期2小时
        redisTemplate.opsForValue().set(cacheKey, recommendations, 2, TimeUnit.HOURS);

        return recommendations;
    }

    private int calculateActivityScore(int browseCount, int clickCount, int purchaseCount,
                                       int favoriteCount, int commentCount) {
        // 简单加权计算活跃度分数
        return browseCount + clickCount * 2 + purchaseCount * 5 +
                favoriteCount * 3 + commentCount * 4;
    }

    private UserProfileVO convertToVO(UserProfile profile) {
        UserProfileVO vo = new UserProfileVO();
        vo.setUserId(profile.getUserId());
        vo.setGender(profile.getGender());
        vo.setAge(profile.getAge());
        vo.setLocation(profile.getLocation());
        vo.setInterests(profile.getInterests());
        vo.setPurchasePower(profile.getPurchasePower());
        vo.setActivityLevel(profile.getActivityLevel());
        vo.setPreferenceCategories(profile.getPreferenceCategories());
        return vo;
    }
}
